<?php

define('INCLUDE_CHECK',true);

require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined


session_name('pocoymallogin');
// Starting the session

session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week

session_start();

if(isset($_SESSION['id']) && !isset($_COOKIE['pocoymalRemember']) && !$_SESSION['rememberMe']) {
    // If you are logged in, but you don't have the pocoymalRemember cookie (browser restart)
    // and you have not checked the rememberMe checkbox:

    $_SESSION = array();
    session_destroy();

    // Destroy the session
}


if(isset($_GET['logoff'])) {
    $_SESSION = array();
    session_destroy();

    header("Location: index.php");
    exit;
}

if(isset($_POST['submit']) && $_POST['submit']=='Login') {
    // Checking whether the Login form has been submitted

    $err = array();
    // Will hold our errors


    if(!$_POST['username'] || !$_POST['password'])
        $err[] = '¡¡Tienes que rellenar todos los campos mandril!!';

    if(!count($err)) {
        $_POST['username'] = mysql_real_escape_string($_POST['username']);
        $_POST['password'] = mysql_real_escape_string($_POST['password']);
        $_POST['rememberMe'] = (int)$_POST['rememberMe'];

        // Escaping all input data

        $row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM pocoymal_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));

        if($row['usr']) {
            // If everything is OK login

            $_SESSION['usr']=$row['usr'];
            $_SESSION['id'] = $row['id'];
            $_SESSION['rememberMe'] = $_POST['rememberMe'];

            // Store some data in the session

            setcookie('pocoymalRemember',$_POST['rememberMe']);
        }
        else $err[]='Has metido la pata en el nombre de usuario y/o contraseña';
    }

    if($err)
        $_SESSION['msg']['login-err'] = implode('<br />',$err);
    // Save the error messages in the session

    header("Location: index.php");
    exit;
}
else if(isset($_POST['submit']) && $_POST['submit']=='Register') {
    // If the Register form has been submitted

    $err = array();

    if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32) {
        $err[]='¡Te has pasadoooo!! El nombre de usuario debe estar entre 3 y 32 caracteres.';
    }

    if(strlen($_POST['password'])<4 || strlen($_POST['password'])>32) {
        $err[]='¡Te has pasadoooo!! La contraseña debe estar entre 3 y 32 caracteres.';
    }

    if(preg_match('/[^a-z0-9\-\_\.\@]+/i',$_POST['password'])) {
        $err[]='Nada de letras raras en las contraseñas...';
    }

    if($_POST['password'] != $_POST['rpassword']) {
        $err[]='¿Sabes escribir dos veces la misma contraseña...? o te ayudo...';
    }

    if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username'])) {
        $err[]='Nada de letras raras en el nombre de usuario...';
    }

    if(!checkEmail($_POST['email'])) {
        $err[]='Como no escribas un email correcto, no poremos enviarte avisos...';
    }

    if($_POST['nbyap'] == "") {
        $err[]='Imagino que tienes nombre y apellidos....';
    }

    if(!checkDNI($_POST['dni'])) {
        $err[]='Algo fue mal con tu DNI. Escríbe 8 CIFRAS poniendo ceros al principio si es necesario y una letra MAY&Uacute;SCULA al final';
    }

    if(!checkMovil($_POST['tlfn'])) {
        $err[]='Algo fue mal con tu M&oacute;vil. Escríbelo bien zoquete';
    }



    if(!count($err)) {
        // If there are no errors

        //$pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
        // Generate a random password

        $_POST['email'] = mysql_real_escape_string($_POST['email']);
        $_POST['username'] = mysql_real_escape_string($_POST['username']);
        $_POST['password'] = mysql_real_escape_string($_POST['password']);
        // Escape the input data


        $pass = $_POST['password'];

        mysql_query("	INSERT INTO pocoymal_members(usr,pass,nbyap,email,dni,num,tlfn,regIP,dt)
						VALUES(

							'".$_POST['username']."',
							'".md5($pass)."',
                                                        '".$_POST['nbyap']."',
							'".$_POST['email']."',
                                                        '".$_POST['dni']."',
                                                        '".$_POST['num']."',
                                                        '".$_POST['tlfn']."',
							'".$_SERVER['REMOTE_ADDR']."',
							NOW()

						)");

        /*        $err[] = "	INSERT INTO semoden_members(usr,pass,email,regIP,dt)
						VALUES(

							'".$_POST['username']."',
							'".md5($pass)."',
							'".$_POST['email']."',
							'".$_SERVER['REMOTE_ADDR']."',
							NOW()

						)"." --> ".$pass;*/

        if(mysql_affected_rows($link)==1) {
            send_mail(	'javier.pelado@gmail.com',
                    $_POST['email'],
                    'Registrado en la página de Poco y Mal',
                    'Tu contraseña es: '.$pass);

            $_SESSION['msg']['reg-success']='Te hemos mandado un correo con tus datos, enhorabuena, ya estás registrado';
        }
        else $err[]='Ese nombre de usuario ya est&aacute; pillado';
    }

    if(count($err)) {
        $_SESSION['msg']['reg-err'] = implode('<br />',$err);
    }

    header("Location: index.php");
    exit;
}

$script = '';

if(isset($_SESSION['msg'])) {
    // The script below shows the sliding panel on page load

    $script = '
	<script type="text/javascript">

		$(function(){

			$("div#panel").show();
			$("#toggle a").toggle();
		});

	</script>';

}
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Portal de jugadores del Poco y Mal</title>

        <link rel="stylesheet" type="text/css" href="css/semoden.css" media="screen" />
        <link rel="stylesheet" type="text/css" href="login_panel/css/slide.css" media="screen" />
        <link rel="stylesheet" type="text/css" href="tools_panel/css/style.css" media="screen" />

        <link rel="stylesheet" type="text/css" media="screen" href="jqGrid/themes/overcast/jquery-ui-1.8.2.custom.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="jqGrid/themes/ui.jqgrid.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="jqGrid/themes/ui.multiselect.css" />


        <script type="text/javascript" src="scripts/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="scripts/jquery.corner.js"></script>
        <script type="text/javascript" src="scripts/jquery.tools.min.js"></script>
        <script type="text/javascript" src="scripts/jscript.js"></script>

        <script src="jqGrid/js/i18n/grid.locale-sp.js" type="text/javascript"></script>
        <script src="jqGrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
        <script src="jqGrid/js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
        <script src="scripts/jquery.validate.js" type="text/javascript"></script>

        <script type="text/javascript">
            $.jgrid.no_legacy_api = true;
            $.jgrid.useJSON = true;
        </script>

        <!-- PNG FIX for IE6 -->
        <!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
        <!--[if lte IE 6]>
            <script type="text/javascript" src="login_panel/js/pngfix/supersleight-min.js"></script>
        <![endif]-->

        <script src="login_panel/js/slide.js" type="text/javascript"></script>

        <?php echo $script; ?>
    </head>

    <body>

        <!-- Panel -->
        <div id="toppanel" style="position: fixed">
            <div id="panel">
                <div class="content clearfix">
                    <div class="left">
                        <h1>POCO Y MAL</h1>
                        <h2>PORTAL PARA JUGADORES DEL POCO Y MAL</h2>
                        <p class="grey">Puedes ver los datos de los demás jugadores, y apuntarte a los partidos de entrenamientos que se planifiquen.</p>
                        <h2>Usadlo bien...</h2>
                    </div>


                    <?php

                    if(!isset($_SESSION['id'])):

                        ?>

                    <div class="left">
                        <!-- Login Form -->
                        <form class="clearfix" action="" method="post">
                            <h1>Acceso de miembros</h1>
                            <p>Todavía no est&aacute;s registrado, <a id="register" src="#" style="cursor: pointer">¡¡Hazlo aqu&Iacute;!!</a></p>

                                <?php

                                if(isset($_SESSION['msg']['login-err']) && $_SESSION['msg']['login-err']) {
                                    echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
                                    unset($_SESSION['msg']['login-err']);
                                }
                                ?>

                            <label class="grey" for="username">Nombre de usuario:</label>
                            <input class="field" type="text" name="username" id="username" value="" size="23" />
                            <label class="grey" for="password">Contraseña:</label>
                            <input class="field" type="password" name="password" id="password" size="23" />
                            <label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> &nbsp;Recordarme</label>
                            <div class="clear"></div>
                            <input type="submit" name="submit" value="Login" class="bt_login" />
                        </form>
                    </div>
                    <script type="text/javascript">

                        $(function(){
                            $("#register").click(function(e) {
                                e.preventDefault();
                                $("#regform").toggle(1000);

                            });

                        });

                    </script>

                        <?php if((isset($_SESSION['msg']['reg-err']) && $_SESSION['msg']['reg-err']) || (isset($_SESSION['msg']['reg-success']) && $_SESSION['msg']['reg-success'])) { ?>
                    <div id="regform" class="left">
                                <?php } else { ?>
                        <div id="regform" class="left" style="display:none;">
                                    <?php } ?>
                            <h1>¡REG&Iacute;STRATE!</h1>
                            <!-- Register Form -->
                            <form id="rform" action="" method="post">

                                    <?php

                                    if(isset($_SESSION['msg']['reg-err']) && $_SESSION['msg']['reg-err']) {
                                        echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
                                        unset($_SESSION['msg']['reg-err']);
                                    }

                                    if(isset($_SESSION['msg']['reg-success']) && $_SESSION['msg']['reg-success']) {
                                        echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
                                        unset($_SESSION['msg']['reg-success']);
                                    }
                                    ?>

                                <label class="grey label" for="username">Nombre de usuario:</label>
                                <input class="field" type="text" name="username" id="username" value="" size="23" />
                                <span class="status"></span>
                                <label class="grey label" for="email">Email:</label>
                                <input class="field" type="text" name="email" id="email" size="23" />
                                <span class="status"></span>
                                <label class="grey label" for="password">Contraseña:</label>
                                <input class="field" type="password" name="password" id="password" size="23" />
                                <span class="status"></span>
                                <label class="grey label" for="retipe_password">Repite contraseña:</label>
                                <input class="field" type="password" name="rpassword" id="rpassword" size="23" />
                                <span class="status"></span>
                                <label class="grey label" for="nbyap">Nombre y Apellidos:</label>
                                <input class="field" type="text" name="nbyap" id="nbyap" size="100" />
                                <span class="status"></span>
                                <label class="grey label" for="dni">DNI:</label>
                                <input class="field" type="text" name="dni" id="dni" size="9" />
                                <span class="status"></span>
                                <label class="grey label" for="tlfn">Tel&eacute;fono m&oacute;vil:</label>
                                <input class="field" type="text" name="tlfn" id="tlfn" size="9" />
                                <span class="status"></span>
                                <label class="grey label" for="num">N&uacute;mero de camiseta:</label>
                                <select name="num" id="num" style="float: left;margin-left: 10px;margin-top: 10px;">
                                <span class="status"></span>
                                <?php
                                for ($i = 0; $i <= 100; $i++) {
                                    echo '<option value="'.$i.'">'.$i.'</option>';
                                    }
                                ?>
                                </select>

                                <label>Te enviaremos un email con tus datos.</label>
                                <input type="submit" name="submit" value="Register" class="bt_register" />
                            </form>
                        </div>

                        <?php

                        else:

                            ?>

                        <div class="right" style="float:right">

                            <h1>Panel de miembros</h1>
                            <div class="container">
                                <p><?php
                                        echo '<strong>Usuario:</strong> '.$_SESSION['usr'].'<br>';
                                        $query = 'SELECT * FROM pocoymal_members WHERE `id`='.$_SESSION['id'];
                                        $result = mysql_query($query);
                                        $row = mysql_fetch_array($result);
                                        echo '<strong>Email:</strong> '.$row['email'];
                                        ?>
                                </p>
                            </div>
                            <script type="text/javascript">show_tools(<?php $_SESSION ?>);</script>
                            <div class="container">
                                <span><a id="profile" href=""><b>Datos Perfil</b></a></span>
                                <span><a href="?logoff"><b>Salir</b></a></span>
                            </div>
                        </div>
                    <script type="text/javascript">
                        $("#profile").click(function() {
                            <?php 
                            $query = 'SELECT * FROM pocoymal_members WHERE `id`='.$_SESSION['id'];
                            $result = mysql_query($query);
                            $row = mysql_fetch_array($result);
                            echo "showUserData('".$row['nbyap']."','".$row['usr']."','".$row['email']."','".$row['dni']."','".$row['num']."','".$row['tlfn']."');";
                            ?>
                            return false;
                        });

                    </script>

                        <div class="left right">
                        </div>

                        <?php
                        endif;
                        ?>
                    </div>
                </div> <!-- /login -->

                <!-- The tab on top -->
                <div class="tab">
                    <ul class="login">
                        <li class="left">&nbsp;</li>
                        <li>¡Hola <?php echo isset($_SESSION['usr']) ? $_SESSION['usr'] : 'Invitado';?>!</li>
                        <li class="sep">|</li>
                        <li id="toggle">
                            <a id="open" class="open" href="#"><?php echo isset($_SESSION['id'])?'Abrir Panel':'Log In | Registrar';?></a>
                            <a id="close" style="display: none;" class="close" href="#">Cerrar Panel</a>
                        </li>
                        <li class="right">&nbsp;</li>
                    </ul>
                </div> <!-- / top -->

            </div> <!--panel -->
